package com.sdx.console.orgmain.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.content.service.ResContentColumnService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.orgmain.entity.*;
import com.sdx.console.orgmain.service.*;
import com.sdx.console.orgmain.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * OrgLecture 接口
 */
@RequestMapping("/orgLecture/orgLecture")
@Controller
public class OrgLectureController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(OrgLectureController.class);
    private static final String MODEL = "/orgLecture/orgLecture";

	@Resource
	private BaseDataService baseDataService;

	@Resource
	private CustomerInfoService customerInfoService;

    @Resource
	private OrgLectureService orgLectureService;

	@Resource
	private ResCloudFileService resCloudFileService;

	@Resource
	private CorePlatformService platformService;

	@Resource
	private CorePlatformService corePlatformService;


	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		view.addObject("provinceList",baseDataService.getAllProvince());
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setIsTeacher(1);
		List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
		view.addObject("customerInfoList",customerInfoList);
		Integer accessType = platformService.getAccessType(request);
		view.addObject("accessType",accessType);
		Integer provinceId =null;
		if (accessType.intValue()<6) {
			CoreOrg currentOrg = corePlatformService.getCurrentOrg();
			provinceId = currentOrg.getProvinceId();
		}
		view.addObject("provinceId",provinceId);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("orgLecture.orgLecture.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("orgLecture.orgLecture.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Long lectureId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        OrgLecture orgLecture = orgLectureService.queryById(lectureId);
        view.addObject("orgLecture", orgLecture);
		setPageParam(view,request);
		try {
			view.addObject("orgLectureJson", JacksonUtils.toJsonString(orgLecture,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("orgLecture.orgLecture.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
		view.addObject("orgLecture", new OrgLecture());
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("orgLecture.orgLecture.query")
    @ResponseBody
    public JsonResult<PageQuery> list(OrgLecture condtion,HttpServletRequest request)
    {
    	Integer accessType = platformService.getAccessType(request);
		if(accessType!=6){
			CoreUser user = getLoginUser(request);
			CoreOrg coreOrg = orgLectureService.selectCoreOrgById(user.getOrgId().intValue());
			if(coreOrg!=null){
				condtion.setProvinceId(coreOrg.getProvinceId());
			}else{
				condtion.setProvinceId(999999);
			}

		}
        PageQuery page = condtion.getPageQuery();
        orgLectureService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,OrgLecture orgLecture,HttpServletRequest request
							,MultipartFile mainImgFile
	) {

    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/lecture/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(mainImgFile)) {
			try
			{
		        String mainImgFileNamePair = FileUtils.upload(subPath,mainImgFile);
		        String mainImgStoreFile = mainImgFileNamePair.split("::")[0];
		        mainImgStoreFile = subPath+mainImgStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+mainImgStoreFile,bucketName,mainImgStoreFile.substring(1));
				String mainImgUrl = "https://sdxcomm."+ConfigService.ossDomain+mainImgStoreFile;
				orgLecture.setMainImg(mainImgUrl);
				//
				CustomerInfo customerInfo = customerInfoService.queryById(orgLecture.getCustomerId());
				if(customerInfo!=null){
					orgLecture.setMainTeacher(customerInfo.getCustomerName());
				}
				resCloudFileService.insertResFile(ResCloudFile.ALI,mainImgStoreFile,mainImgUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);
		Integer accessType = platformService.getAccessType(request);
    	if (isNew) {
			if(accessType!=6){
				CoreOrg coreOrg = orgLectureService.selectCoreOrgById(user.getOrgId().intValue());
				orgLecture.setProvinceId(coreOrg.getProvinceId());
			}
			orgLecture.setCreatedBy(String.valueOf(user.getId().intValue()));
			orgLecture.setCreatedName(user.getName());
			orgLecture.setCreatedTime(new Date());
			orgLecture.setUpdatedBy(String.valueOf(user.getId().intValue()));
			orgLecture.setUpdatedName(user.getName());
			orgLecture.setUpdatedTime(new Date());
			orgLectureService.save(orgLecture);
		} else {
			orgLecture.setUpdatedBy(String.valueOf(user.getId().intValue()));
			orgLecture.setUpdatedName(user.getName());
			orgLecture.setUpdatedTime(new Date());
			orgLectureService.updateTemplate(orgLecture);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("orgLecture.orgLecture.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)OrgLecture orgLecture,HttpServletRequest request
							,@RequestParam("mainImgFile") MultipartFile mainImgFile
		)
    {

        return save(true,orgLecture,request
					,mainImgFile
		);
    }

    @PostMapping("/update.json")
    @Function("orgLecture.orgLecture.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  OrgLecture orgLecture,HttpServletRequest request
							,@RequestParam("mainImgFile") MultipartFile mainImgFile) {
		CustomerInfo customerInfo = customerInfoService.queryById(orgLecture.getCustomerId());
		if(customerInfo!=null){
			orgLecture.setMainTeacher(customerInfo.getCustomerName());
		}
		if(StringUtils.isEmpty(orgLecture.getLectureImgs())|| StringUtils.equals("@",orgLecture.getLectureImgs())){
			orgLecture.setLectureImgs(",");
		}
		return save(false,orgLecture,request,mainImgFile);
    }


   
    @GetMapping("/view.json")
    @Function("orgLecture.orgLecture.query")
    @ResponseBody
    public JsonResult<OrgLecture>queryInfo(Long lectureId) {
        OrgLecture orgLecture = orgLectureService.queryById( lectureId);
        return  JsonResult.success(orgLecture);
    }

    @PostMapping("/delete.json")
    @Function("orgLecture.orgLecture.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        orgLectureService.batchDelOrgLecture(idList);
        return JsonResult.success();
    }

	/**
	 *  图片上传
	 * @param file
	 * @return
	 */
	@RequestMapping("/upload.json")
	@ResponseBody
	public JSONObject uploadImg(MultipartFile file) {
		JSONObject jsobject = new JSONObject();
		String dir = DateUtil.now("yyyyMMdd");
		String subPath = "/images/lecture/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(file)) {
			try
			{
				String fileNamePair = FileUtils.upload(subPath,file);
				String storeFile = fileNamePair.split("::")[0];
				storeFile = subPath+storeFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
				String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
				jsobject.put("url",url);
				jsobject.put("state", "SUCCESS");
				jsobject.put("title", "");
				jsobject.put("original", "");
				resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","学校logo");
			}catch(Exception e) {
				e.printStackTrace();
				jsobject.put("state", "FAIL");
				jsobject.put("title", "");
				jsobject.put("original", "");
				jsobject.put("url","");
			}
		}
		return jsobject;
	}

	/**
	 * 返回 ueditor 图片上传的配置参数
	 * @return
	 */
	@RequestMapping("/config")
	@ResponseBody
	public String config(){
		String UEDITOR_CONFIG = "{\n" +
				"    \"imageActionName\": \"uploadimage\",\n" +
				"    \"imageFieldName\": \"file\",\n" +
				"    \"imageMaxSize\": 2048000,\n" +
				"    \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
				"    \"imageCompressEnable\": true,\n" +
				"    \"imageCompressBorder\": 1600,\n" +
				"    \"imageInsertAlign\": \"none\",\n" +
				"    \"imageUrlPrefix\": \"\",\n" +
				"    \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
				"\n" +
				"    \"scrawlActionName\": \"uploadscrawl\",\n" +
				"    \"scrawlFieldName\": \"file\",\n" +
				"    \"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
				"    \"scrawlMaxSize\": 2048000,\n" +
				"    \"scrawlUrlPrefix\": \"\",\n" +
				"    \"scrawlInsertAlign\": \"none\",\n" +
				"\n" +
				"    \"snapscreenActionName\": \"uploadimage\",\n" +
				"    \"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
				"    \"snapscreenUrlPrefix\": \"\",\n" +
				"    \"snapscreenInsertAlign\": \"none\",\n" +
				"\n" +
				"    \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
				"    \"catcherActionName\": \"catchimage\",\n" +
				"    \"catcherFieldName\": \"source\",\n" +
				"    \"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
				"    \"catcherUrlPrefix\": \"\",\n" +
				"    \"catcherMaxSize\": 2048000,\n" +
				"    \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
				"\n" +
				"    \"videoActionName\": \"uploadvideo\",\n" +
				"    \"videoFieldName\": \"upfile\",\n" +
				"    \"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
				"    \"videoUrlPrefix\": \"\",\n" +
				"    \"videoMaxSize\": 102400000,\n" +
				"    \"videoAllowFiles\": [\n" +
				"        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
				"        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"],\n" +
				"\n" +
				"    \"fileActionName\": \"uploadfile\",\n" +
				"    \"fileFieldName\": \"upfile\",\n" +
				"    \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
				"    \"fileUrlPrefix\": \"\",\n" +
				"    \"fileMaxSize\": 51200000,\n" +
				"    \"fileAllowFiles\": [\n" +
				"        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
				"        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
				"        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
				"        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
				"        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
				"    ],\n" +
				"\n" +
				"    \"imageManagerActionName\": \"listimage\",\n" +
				"    \"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
				"    \"imageManagerListSize\": 20,\n" +
				"    \"imageManagerUrlPrefix\": \"\",\n" +
				"    \"imageManagerInsertAlign\": \"none\",\n" +
				"    \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
				"\n" +
				"    \"fileManagerActionName\": \"listfile\",\n" +
				"    \"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
				"    \"fileManagerUrlPrefix\": \"\",\n" +
				"    \"fileManagerListSize\": 20,\n" +
				"    \"fileManagerAllowFiles\": [\n" +
				"        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
				"        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
				"        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
				"        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
				"        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
				"    ] \n" +
				"\n" +
				"}";
		return UEDITOR_CONFIG;
	}

}
